<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="宗祠名称" prop="templeName">
          <el-input v-model="queryParams.templeName" placeholder="宗祠名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button v-hasPerm="['genealogy:temple-info:add']" type="success" icon="plus" @click="handleOpenDialog()">
          新增
        </el-button>
        <el-button v-hasPerm="['genealogy:temple-info:delete']" type="danger" :disabled="removeIds.length === 0"
          @click="handleDelete()">
          删除
        </el-button>
      </div>

      <el-table ref="dataTableRef" v-loading="loading" :data="pageData" highlight-current-row border
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column key="id" label="宗祠ID" prop="id" min-width="80" align="center" />
        <el-table-column key="templeName" label="宗祠名称" prop="templeName" min-width="150" align="center" />
        <el-table-column key="location" label="宗祠位置" prop="location" min-width="150" align="center" />
        <el-table-column key="manager" label="联系人" prop="manager" min-width="100" align="center" />
        <el-table-column key="managerPhone" label="联系电话" prop="managerPhone" min-width="120" align="center" />
        <el-table-column key="status" label="状态" prop="status" min-width="80" align="center" />
        <el-table-column key="createTime" label="创建时间" prop="createTime" min-width="150" align="center" />
        <el-table-column key="updateTime" label="更新时间" prop="updateTime" min-width="150" align="center" />

        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-col>
              <el-button type="info" size="small" link @click="handleViewDialog(scope.row.id)">
                <template #icon>
                  <View />
                </template>
                查看
              </el-button>
            </el-col>
            <el-col>
              <el-button v-hasPerm="['genealogy:temple-info:edit']" type="primary" size="small" link
                @click="handleOpenDialog(scope.row.id)">
                <template #icon>
                  <Edit />
                </template>
                编辑
              </el-button>
            </el-col>
            <el-col>
              <el-button v-hasPerm="['genealogy:temple-info:delete']" type="danger" size="small" link
                @click="handleDelete(scope.row.id)">
                <template #icon>
                  <Delete />
                </template>
                删除
              </el-button>
            </el-col>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="handleQuery()" />
    </el-card>

    <!-- 宗祠信息表单弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" :size="drawerSize" title="Tips"
      @close="handleCloseDialog">
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="宗祠名称" prop="templeName">
          <el-input v-model="formData.templeName" placeholder="宗祠名称" :disabled="isViewMode" />
        </el-form-item>

        <el-form-item label="副标题" prop="subTitle">
          <el-input v-model="formData.subTitle" placeholder="副标题" :disabled="isViewMode" />
        </el-form-item>

        <el-form-item label="宗祠位置" prop="location">
          <el-input v-model="formData.location" placeholder="宗祠位置" :readonly="formData.longitude && formData.latitude"
            :disabled="formData.longitude && formData.latitude || isViewMode">
            <template #append v-if="formData.longitude && formData.latitude">
              <el-tooltip content="已通过地图选点获取地址">
                <el-icon>
                  <Location />
                </el-icon>
              </el-tooltip>
            </template>
          </el-input>
          <div v-if="!(formData.longitude && formData.latitude)" class="location-tip">请在下方地图中选择位置以自动填充地址</div>
        </el-form-item>

        <el-form-item label="地理位置">
          <div class="map-container">
            <div id="map-container" class="amap-wrapper"></div>
            <div class="map-info">
              <p>经度: {{ formData.longitude }}</p>
              <p>纬度: {{ formData.latitude }}</p>
              <el-button type="primary" size="small" @click="showMapDialog = true"
                :disabled="isViewMode">选择位置</el-button>
            </div>
          </div>

          <el-dialog v-model="showMapDialog" title="选择位置" width="80%" :destroy-on-close="true">
            <div class="map-search-container">
              <el-input v-model="searchAddress" placeholder="输入地址搜索位置" clearable @keyup.enter="searchLocation">
                <template #append>
                  <el-button @click="searchLocation">
                    <el-icon>
                      <Search />
                    </el-icon>
                  </el-button>
                </template>
              </el-input>
              <div v-if="searchResults.length > 0" class="search-results">
                <div v-for="(item, index) in searchResults" :key="index" class="search-result-item"
                  @click="useSearchResult(item)">
                  {{ item.formattedAddress }}
                </div>
              </div>
            </div>
            <div style="height: 500px">
              <div id="map-dialog" style="height: 100%"></div>
            </div>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="showMapDialog = false">取消</el-button>
                <el-button type="primary" @click="confirmLocation">确定</el-button>
              </span>
            </template>
          </el-dialog>
        </el-form-item>

        <el-form-item label="宗祠简介" prop="intro">
          <el-input v-model="formData.intro" type="textarea" :rows="3" placeholder="宗祠简介" :disabled="isViewMode" />
        </el-form-item>

        <el-form-item label="封面图片" prop="coverImage">
          <SingleImageUpload v-model="formData.coverImage" :disabled="isViewMode" />
        </el-form-item>

        <el-form-item label="图片集" prop="imageArray">
          <el-upload v-model:file-list="imageFileList" list-type="picture-card" :http-request="handleImageUpload"
            :on-success="handleImageSuccess" :on-remove="handleImageRemove" :on-preview="handleImagePreview" multiple
            :limit="3" :disabled="isViewMode">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>

          <!-- 图片预览 -->
          <el-dialog v-model="previewVisible" title="预览图片">
            <img w-full :src="previewImage" alt="预览图片" style="max-width: 100%; max-height: 500px;" />
          </el-dialog>
        </el-form-item>

        <el-form-item label="历史沿革">
          <div class="history-list">
            <div v-for="(item, index) in historyList" :key="index" class="history-item">
              <el-row :gutter="10">
                <el-col :span="6">
                  <el-input v-model="item.year" placeholder="年份" :disabled="isViewMode" />
                </el-col>
                <el-col :span="16">
                  <el-input v-model="item.content" placeholder="历史事件描述" :disabled="isViewMode" />
                </el-col>
                <el-col :span="2">
                  <el-button type="danger" @click="removeHistoryItem(index)" :icon="Delete" circle
                    v-if="!isViewMode"></el-button>
                </el-col>
              </el-row>
            </div>
            <div class="mt-10px">
              <el-button type="primary" @click="addHistoryItem" size="small" v-if="!isViewMode">添加历史记录</el-button>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="负责人" prop="manager">
          <el-input v-model="formData.manager" placeholder="负责人" :disabled="isViewMode" />
        </el-form-item>

        <el-form-item label="负责人电话" prop="managerPhone">
          <el-input v-model="formData.managerPhone" placeholder="负责人电话" :disabled="isViewMode" />
        </el-form-item>

        <el-form-item label="供稿人" prop="contributor">
          <el-input v-model="formData.contributor" placeholder="供稿人" :disabled="isViewMode" />
        </el-form-item>

        <el-form-item label="开放时间" prop="openingHours">
          <el-input v-model="formData.openingHours" placeholder="开放时间" :disabled="isViewMode" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态" :disabled="isViewMode">
            <el-option :value="1" label="启用" />
            <el-option :value="0" label="禁用" />
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="notes">
          <el-input v-model="formData.notes" type="textarea" :rows="2" placeholder="备注" :disabled="isViewMode" />
        </el-form-item>
      </el-form>
      <template #footer v-if="!isViewMode">
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 宗祠信息详情内容展示 -->
    <el-dialog v-model="templeVisible" class="temple-detail-dialog" title="宗祠详情信息"
      width="375px" :destroy-on-close="true" @close="handleCloseTempleDetail">
      <div v-if="currentTemple" class="temple-detail-container">
        <!-- 顶部大图 -->
        <div class="hero-section">
          <div class="hero-image" v-if="currentTemple.coverImage">
            <img :src="currentTemple.coverImage" :alt="currentTemple.templeName">
          </div>
          <div class="hero-overlay">
            <h1 class="hero-title">{{ currentTemple.templeName }}</h1>
            <p class="hero-subtitle" v-if="currentTemple.subTitle">{{ currentTemple.subTitle }}</p>
          </div>
        </div>

        <!-- 信息卡片 -->
        <div class="info-cards">
          <!-- 基本资料卡片 -->
          <div class="info-card">
            <div class="card-header">
              <i class="icon-info"></i>
              <span>基本资料</span>
            </div>
            <div class="card-content">
              <div class="info-item">
                <span class="label">宗祠名称</span>
                <span class="value">{{ currentTemple.templeName }}</span>
              </div>
              <div class="info-item" v-if="currentTemple.subTitle">
                <span class="label">副标题</span>
                <span class="value">{{ currentTemple.subTitle }}</span>
              </div>
              <div class="info-item">
                <span class="label">宗祠位置</span>
                <span class="value">{{ currentTemple.location }}</span>
              </div>
              <div class="info-item">
                <span class="label">负责人</span>
                <span class="value">{{ currentTemple.manager }}</span>
              </div>
              <div class="info-item">
                <span class="label">联系电话</span>
                <span class="value">{{ currentTemple.managerPhone }}</span>
              </div>
              <div class="info-item">
                <span class="label">开放时间</span>
                <span class="value">{{ currentTemple.openingHours || '暂无信息' }}</span>
              </div>
              <div class="info-item">
                <span class="label">状态</span>
                <span class="value">
                  <span class="status-badge" :class="currentTemple.status === 1 ? 'active' : 'inactive'">
                    {{ currentTemple.status === 1 ? '启用' : '禁用' }}
                  </span>
                </span>
              </div>
            </div>
          </div>

          <!-- 地理位置卡片 -->
          <div class="info-card" v-if="currentTemple.longitude && currentTemple.latitude">
            <div class="card-header">
              <i class="icon-location"></i>
              <span>地理位置</span>
            </div>
            <div class="card-content">
              <div class="map-container">
                <div class="mini-map" id="temple-mini-map"></div>
                <!-- <div class="coordinates">
                  <span>经度：{{ currentTemple.longitude }}</span>
                  <span>纬度：{{ currentTemple.latitude }}</span>
                </div> -->
              </div>
            </div>
          </div>

          <!-- 宗祠简介卡片 -->
          <div class="info-card" v-if="currentTemple.intro">
            <div class="card-header">
              <i class="icon-intro"></i>
              <span>宗祠简介</span>
            </div>
            <div class="card-content">
              <div class="intro-text">
                {{ currentTemple.intro }}
              </div>
            </div>
          </div>

          <!-- 图片展示卡片 -->
          <div class="info-card" v-if="templeImages && templeImages.length > 0">
            <div class="card-header">
              <i class="icon-images"></i>
              <span>图片展示</span>
              <span class="image-count">{{ templeImages.length }}张</span>
            </div>
            <div class="card-content">
              <div class="image-grid">
                <div v-for="(image, index) in templeImages" :key="index" class="image-item">
                  <img :src="image" :alt="'宗祠图片' + (index + 1)" @click="previewImageDetail(image)">
                </div>
              </div>
            </div>
          </div>

          <!-- 历史沿革卡片 -->
          <div class="info-card" v-if="templeHistory && templeHistory.length > 0">
            <div class="card-header">
              <i class="icon-history"></i>
              <span>历史沿革</span>
            </div>
            <div class="card-content">
              <div class="timeline">
                <div v-for="(item, index) in templeHistory" :key="index" class="timeline-item">
                  <div class="timeline-dot"></div>
                  <div class="timeline-content">
                    <div class="timeline-year">{{ item.year }}</div>
                    <div class="timeline-text">{{ item.content }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 备注卡片 -->
          <div class="info-card" v-if="currentTemple.notes">
            <div class="card-header">
              <i class="icon-notes"></i>
              <span>备注信息</span>
            </div>
            <div class="card-content">
              <div class="notes-text">
                {{ currentTemple.notes }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 图片预览弹窗 -->
      <el-dialog v-model="detailPreviewVisible" title="图片预览" width="60%" custom-class="image-preview-dialog">
        <img :src="detailPreviewImage" :alt="'宗祠图片预览'" class="preview-large-image">
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script setup>
import TempleAPI from "@/api/genealogy/temple.api";
import FileAPI from "@/api/file.api";
import { ElMessage, ElMessageBox } from "element-plus";
import { DeviceEnum } from "@/enums/index.js";
import { useAppStore } from "@/store";
import { Delete, Edit, Plus, Location, Search, View } from "@element-plus/icons-vue";
import { onMounted, onUnmounted, nextTick, watch, computed, ref } from 'vue';
import SingleImageUpload from "@/components/Upload/SingleImageUpload.vue";

defineOptions({
  name: "Temple",
  inheritAttrs: false,
});

const appStore = useAppStore();
const drawerSize = computed(() => {
  if (isViewMode.value) {
    return "900px";
  }
  return appStore.device === DeviceEnum.DESKTOP ? "600px" : "90%";
});
const queryFormRef = ref();
const dataFormRef = ref();
const templeVisible = ref(false);
const loading = ref(false);
const removeIds = ref([]);
const total = ref(0);

const queryParams = reactive({
  templeName: "",
  pageNum: 1,
  pageSize: 10,
});

// 宗祠信息表格数据
const pageData = ref([]);

// 弹窗
const dialog = reactive({
  title: "新增宗祠",
  visible: false,
});

// 初始宗祠表单数据
const initialFormData = {
  id: undefined,
  templeName: "",
  subTitle: "",
  location: "",
  longitude: null,
  latitude: null,
  intro: "",
  coverImage: "",
  imageArray: "",
  historyArray: "",
  manager: "",
  managerPhone: "",
  contributor: "",
  openingHours: "",
  status: 1,
  notes: "",
};

// 宗祠信息表单数据
const formData = ref({ ...initialFormData });

// 宗祠信息表单校验规则
const rules = reactive({
  templeName: [{ required: true, message: "请输入宗祠名称", trigger: "blur" }],
  location: [{ required: true, message: "请输入宗祠位置", trigger: "blur" }],
  manager: [{ required: true, message: "请输入管理员", trigger: "blur" }],
  managerPhone: [
    { required: true, message: "请输入管理员电话", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
  ],
});

// 历史沿革列表
const historyList = ref([]);

// 高德地图相关
const showMapDialog = ref(false);
let map = null;
let dialogMap = null;
let marker = null;
let tempLocation = { lng: null, lat: null };
const searchAddress = ref(''); // 搜索地址输入
const searchResults = ref([]); // 搜索结果列表

// 高德地图密钥
const AMAP_WEB_API_KEY = '9c5a053254c95d14843efc080ac74f78'; // Web端(JS API)密钥，用于前端地图加载
const AMAP_SECURITY_CODE = '59173e03758c881beab7c813d3a25329'; // 安全密钥

// 图片上传相关变量
const imageFileList = ref([]);
const previewVisible = ref(false);
const previewImage = ref('');

// 查看模式
const isViewMode = ref(false);

// 宗祠详情相关变量
const currentTemple = ref(null);
const templeImages = ref([]);
const templeHistory = ref([]);
const detailPreviewVisible = ref(false);
const detailPreviewImage = ref('');
let miniMap = null;

// 初始化图片数组
function initImageArray() {
  if (formData.value.imageArray) {
    // 将逗号分隔的字符串转为数组，并处理路径格式
    const images = formData.value.imageArray.split(',').filter(url => url.trim()).map(url => {
      const path = url.trim().replace(/\\/g, '/');
      return {
        name: path.substring(path.lastIndexOf('/') + 1),
        url: path
      };
    });
    imageFileList.value = images;
  } else {
    imageFileList.value = [];
  }
}

// 处理图片上传
function handleImageUpload(options) {
  const file = options.file;
  const formData = new FormData();
  formData.append('file', file);

  return FileAPI.upload(formData)
    .then(res => {
      return res;
    })
    .catch(error => {
      ElMessage.error('上传失败: ' + error.message);
      throw error;
    });
}

// 上传成功回调
function handleImageSuccess(res, file) {
  ElMessage.success('上传成功');

  // 更新formData中的imageArray
  if (!formData.value.imageArray) {
    formData.value.imageArray = res.url;
  } else {
    formData.value.imageArray += ',' + res.url;
  }
}

// 删除图片
function handleImageRemove(file) {
  // 从文件列表中移除
  const fileUrl = file.url;
  FileAPI.delete(fileUrl).then(() => {
    ElMessage.success('删除成功');

    // 更新formData中的imageArray
    if (formData.value.imageArray) {
      const images = formData.value.imageArray.split(',');
      const index = images.findIndex(url => url.trim().replace(/\\/g, '/') === fileUrl);
      if (index !== -1) {
        images.splice(index, 1);
        formData.value.imageArray = images.join(',');
      }
    }
  }).catch(error => {
    ElMessage.error('删除失败: ' + error.message);
  });
}

// 预览图片
function handleImagePreview(file) {
  previewImage.value = file.url;
  previewVisible.value = true;
}

// 添加历史记录项
function addHistoryItem() {
  historyList.value.push({
    year: '',
    content: ''
  });
}

// 删除历史记录项
function removeHistoryItem(index) {
  historyList.value.splice(index, 1);
}

/** 查询宗祠信息 */
function handleQuery() {
  loading.value = true;
  TempleAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置宗祠信息查询 */
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection) {
  removeIds.value = selection.map((item) => item.id);
}

// 加载高德地图脚本
function loadAMap() {
  return new Promise((resolve, reject) => {
    // 设置安全密钥
    window._AMapSecurityConfig = {
      securityJsCode: AMAP_SECURITY_CODE
    };

    // 直接加载高德地图JS API
    const script = document.createElement('script');
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${AMAP_WEB_API_KEY}&plugin=AMap.Geocoder`;
    script.async = true;

    script.onload = () => {
      console.log('高德地图API加载成功');
      resolve(window.AMap);
    };

    script.onerror = (error) => {
      console.error('高德地图API加载失败', error);
      ElMessage.error('高德地图加载失败，请检查网络连接');
      reject(error);
    };

    document.head.appendChild(script);
  });
}

// 初始化地图
function initMap() {
  console.log('初始化地图', document.getElementById('map-container'));
  // 确保DOM元素存在
  if (!document.getElementById('map-container')) {
    console.error('地图容器元素不存在');
    return;
  }

  if (!window.AMap) {
    loadAMap().then(() => {
      setTimeout(() => initMap(), 500);
    }).catch(error => {
      console.error('加载高德地图失败', error);
    });
    return;
  }

  try {
    // 创建地图
    map = new AMap.Map('map-container', {
      zoom: 11,
      resizeEnable: true,
      center: [116.397428, 39.90923] // 默认显示北京
    });

    // 如果有经纬度则显示标记
    if (formData.value.longitude && formData.value.latitude) {
      marker = new AMap.Marker({
        position: [formData.value.longitude, formData.value.latitude],
        map: map
      });
      map.setCenter([formData.value.longitude, formData.value.latitude]);
    }
  } catch (error) {
    console.error('创建地图失败', error);
  }
}

// 初始化对话框中的地图
function initDialogMap() {
  console.log('初始化对话框地图', document.getElementById('map-dialog'));
  // 确保DOM元素存在
  if (!document.getElementById('map-dialog')) {
    console.error('对话框地图容器元素不存在');
    return;
  }

  if (!window.AMap) {
    loadAMap().then(() => {
      setTimeout(() => initDialogMap(), 500);
    }).catch(error => {
      console.error('加载高德地图失败', error);
    });
    return;
  }

  try {
    // 创建地图
    dialogMap = new AMap.Map('map-dialog', {
      zoom: 11,
      resizeEnable: true,
      center: [116.397428, 39.90923] // 默认显示北京
    });

    // 如果有经纬度则设置中心点
    if (formData.value.longitude && formData.value.latitude) {
      dialogMap.setCenter([formData.value.longitude, formData.value.latitude]);
      tempLocation = {
        lng: formData.value.longitude,
        lat: formData.value.latitude
      };

      // 添加标记
      new AMap.Marker({
        position: [formData.value.longitude, formData.value.latitude],
        map: dialogMap
      });
    }

    // 添加点击事件
    dialogMap.on('click', function (e) {
      // 清除之前的标记
      dialogMap.clearMap();

      // 添加新标记
      new AMap.Marker({
        position: [e.lnglat.getLng(), e.lnglat.getLat()],
        map: dialogMap
      });

      // 保存临时位置
      tempLocation = {
        lng: e.lnglat.getLng(),
        lat: e.lnglat.getLat()
      };

      // 获取地址信息
      getAddressFromLocation(e.lnglat.getLng(), e.lnglat.getLat());
    });
  } catch (error) {
    console.error('创建对话框地图失败', error);
  }
}

// 通过经纬度获取地址
function getAddressFromLocation(lng, lat) {
  if (!window.AMap) {
    console.error('AMap未加载，无法获取地址');
    return;
  }

  try {
    const geocoder = new AMap.Geocoder({
      city: '全国'
    });

    geocoder.getAddress([lng, lat], function (status, result) {
      console.log('获取地址信息', status, result);
      if (status === 'complete' && result.info === 'OK') {
        // 使用地址信息
        if (result.regeocode && result.regeocode.formattedAddress) {
          formData.value.location = result.regeocode.formattedAddress;
          formData.value.longitude = lng;
          formData.value.latitude = lat;
          console.log('地址已自动填充:', formData.value.location);
        }
      } else {
        // 如果获取地址失败，使用坐标作为地址
        formData.value.location = `坐标位置(${lng.toFixed(6)}, ${lat.toFixed(6)})`;
        formData.value.longitude = lng;
        formData.value.latitude = lat;
        console.log('使用坐标作为地址信息:', formData.value.location);

        if (result && result.info === 'USERKEY_PLAT_NOMATCH') {
          ElMessage.error('高德地图密钥与平台不匹配，请检查密钥设置');
        } else {
          ElMessage.warning('获取地址信息失败，请重试或手动输入地址');
        }
      }
    });
  } catch (error) {
    console.error('获取地址信息失败:', error);
    formData.value.location = `坐标位置(${lng.toFixed(6)}, ${lat.toFixed(6)})`;
    formData.value.longitude = lng;
    formData.value.latitude = lat;
  }
}

// 确认位置选择
function confirmLocation() {
  if (tempLocation.lng && tempLocation.lat) {
    formData.value.longitude = tempLocation.lng;
    formData.value.latitude = tempLocation.lat;

    // 更新小地图上的标记
    if (map) {
      map.clearMap();
      marker = new AMap.Marker({
        position: [tempLocation.lng, tempLocation.lat],
        map: map
      });
      map.setCenter([tempLocation.lng, tempLocation.lat]);
    }
  }
  showMapDialog.value = false;
}

/** 打开宗祠信息弹窗 */
function handleOpenDialog(id) {
  dialog.visible = true;
  historyList.value = [];

  if (id) {
    dialog.title = "修改宗祠信息";
    TempleAPI.getFormData(id).then((data) => {
      Object.assign(formData.value, data);

      // 初始化图片数组
      initImageArray();

      // 解析historyArray为列表
      if (formData.value.historyArray) {
        try {
          historyList.value = JSON.parse(formData.value.historyArray);
        } catch (e) {
          console.error('解析历史沿革数据失败', e);
        }
      }

      // 确保高德地图加载完成后再初始化地图
      nextTick(() => {
        // 延迟初始化地图，确保DOM已渲染
        setTimeout(() => {
          if (window.AMap) {
            if (map) {
              map.destroy();
              map = null;
            }
            initMap();
          } else {
            loadAMap().then(() => {
              initMap();
            }).catch(error => {
              console.error('加载高德地图失败', error);
            });
          }
        }, 500);
      });
    });
  } else {
    dialog.title = "新增宗祠信息";
    formData.value = { ...initialFormData };
    imageFileList.value = []; // 清空文件列表

    // 确保高德地图加载完成后再初始化地图
    nextTick(() => {
      // 延迟初始化地图，确保DOM已渲染
      setTimeout(() => {
        if (window.AMap) {
          if (map) {
            map.clearMap();
          } else {
            initMap();
          }
        } else {
          loadAMap().then(() => {
            initMap();
          }).catch(error => {
            console.error('加载高德地图失败', error);
          });
        }
      }, 500);
    });
  }
}

/** 提交宗祠信息表单 */
function handleSubmit() {
  // 将历史记录列表转为JSON字符串
  formData.value.historyArray = JSON.stringify(historyList.value);

  dataFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;
      const id = formData.value.id;
      if (id) {
        TempleAPI.update(id, formData.value)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        TempleAPI.create(formData.value)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭宗祠信息弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  isViewMode.value = false;
  dataFormRef.value?.resetFields();
  dataFormRef.value?.clearValidate();
  formData.value = { ...initialFormData };
  historyList.value = [];

  // 如果地图实例存在，销毁它们
  destroyAllMapInstances();
}

// 销毁所有地图实例
function destroyAllMapInstances() {
  // 销毁地图实例
  if (map) {
    try {
      map.destroy();
    } catch (error) {
      console.error('销毁地图实例失败', error);
    }
    map = null;
  }

  // 销毁对话框地图实例
  if (dialogMap) {
    try {
      dialogMap.destroy();
    } catch (error) {
      console.error('销毁对话框地图实例失败', error);
    }
    dialogMap = null;
  }
}

/** 删除宗祠信息 */
function handleDelete(id) {
  const ids = id || removeIds.value.join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      TempleAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 搜索地址功能
function searchLocation() {
  if (!searchAddress.value || !window.AMap) return;

  AMap.plugin('AMap.Geocoder', function () {
    const geocoder = new AMap.Geocoder({
      city: '全国'
    });

    geocoder.getLocation(searchAddress.value, function (status, result) {
      if (status === 'complete' && result.info === 'OK') {
        if (result.geocodes && result.geocodes.length > 0) {
          // 保存搜索结果
          searchResults.value = result.geocodes;

          // 如果只有一个结果，直接使用
          if (result.geocodes.length === 1) {
            useSearchResult(result.geocodes[0]);
          }
        } else {
          ElMessage.warning('未找到匹配的地址');
          searchResults.value = [];
        }
      } else {
        ElMessage.error('地址搜索失败');
        searchResults.value = [];
      }
    });
  });
}

// 使用搜索结果
function useSearchResult(item) {
  if (!dialogMap || !item || !item.location) return;

  // 获取位置信息
  const location = item.location;
  tempLocation = {
    lng: location.lng,
    lat: location.lat
  };

  // 清除之前的标记
  dialogMap.clearMap();

  // 在地图上添加标记
  new AMap.Marker({
    position: [location.lng, location.lat],
    map: dialogMap
  });

  // 设置地图中心点
  dialogMap.setCenter([location.lng, location.lat]);
  dialogMap.setZoom(15);

  // 设置位置信息
  formData.value.location = item.formattedAddress;
  formData.value.longitude = location.lng;
  formData.value.latitude = location.lat;

  // 清空搜索结果
  searchResults.value = [];
}

// 监听对话框关闭，清空搜索内容和结果
watch(showMapDialog, (newVal) => {
  if (newVal) {
    // 延迟初始化对话框地图，确保DOM已渲染
    nextTick(() => {
      setTimeout(() => {
        if (window.AMap) {
          initDialogMap();
        } else {
          loadAMap().then(() => {
            initDialogMap();
          }).catch(error => {
            console.error('加载高德地图失败', error);
          });
        }
      }, 500);
    });
  } else {
    // 对话框关闭时，清空搜索内容和结果
    searchAddress.value = '';
    searchResults.value = [];
  }
});

// 组件挂载后加载地图
onMounted(() => {
  handleQuery();
  // 尝试预加载高德地图脚本
  loadAMap().catch(error => {
    console.error('预加载高德地图失败', error);
  });
});

// 组件卸载前销毁地图实例和清理资源
onUnmounted(() => {
  destroyAllMapInstances();
});

// 使用Web服务API进行地址查询（示例函数，如果需要通过后端调用高德Web服务）
function queryAddressByWebService(lng, lat) {
  // 此函数示范如何使用Web服务密钥进行服务端API调用
  // 实际项目中，应该在后端使用此密钥调用高德Web服务API
  const url = `https://restapi.amap.com/v3/geocode/regeo?key=${AMAP_WEB_SERVICE_KEY}&location=${lng},${lat}&output=json`;

  console.log('将使用Web服务密钥通过后端调用:', url);
  ElMessage.info('注意: Web服务密钥应在后端使用，前端直接调用可能存在安全隐患');

  // 实际项目中，应该通过后端服务调用高德Web服务API
  // return axios.get('/api/geocode', { params: { lng, lat } });
}

function handleViewDialog(id) {
  TempleAPI.getFormData(id)
    .then(data => {
      currentTemple.value = data;
      templeVisible.value = true;
      // 处理图片集
      if (data.imageArray) {
        templeImages.value = data.imageArray.split(',').filter(url => url.trim());
      } else {
        templeImages.value = [];
      }
      
      // 处理历史沿革
      if (data.historyArray) {
        try {
          templeHistory.value = JSON.parse(data.historyArray);
        } catch (e) {
          templeHistory.value = [];
        }
      } else {
        templeHistory.value = [];
      }
      
      templeVisible.value = true;
      
      // 延迟初始化地图
      nextTick(() => {
        setTimeout(() => {
          if (currentTemple.value.longitude && currentTemple.value.latitude) {
            initMiniMap();
          }
        }, 300);
      });
    })
    .catch(error => {
      ElMessage.error('获取宗祠详情失败: ' + error.message);
    })
    .finally(() => {
      loading.value = false;
    });
}

// 初始化迷你地图
function initMiniMap() {
  if (!currentTemple.value.longitude || !currentTemple.value.latitude) return;
  
  if (!window.AMap) {
    loadAMap().then(() => {
      setTimeout(() => initMiniMap(), 500);
    }).catch(error => {
      console.error('加载高德地图失败', error);
    });
    return;
  }

  try {
    const container = document.getElementById('temple-mini-map');
    if (!container) return;

    miniMap = new AMap.Map('temple-mini-map', {
      zoom: 15,
      resizeEnable: true,
      center: [currentTemple.value.longitude, currentTemple.value.latitude],
      dragEnable: false,
      zoomEnable: false,
      doubleClickZoom: false,
      keyboardEnable: false
    });

    new AMap.Marker({
      position: [currentTemple.value.longitude, currentTemple.value.latitude],
      map: miniMap
    });
  } catch (error) {
    console.error('创建迷你地图失败', error);
  }
}

// 关闭宗祠详情弹窗
function handleCloseTempleDetail() {
  currentTemple.value = null;
  templeImages.value = [];
  templeHistory.value = [];
  
  // 销毁迷你地图
  if (miniMap) {
    miniMap.destroy();
    miniMap = null;
  }
}

// 预览图片详情
function previewImageDetail(imageUrl) {
  detailPreviewImage.value = imageUrl;
  detailPreviewVisible.value = true;
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.map-search-container {
  margin-bottom: 15px;
  position: relative;
}

.search-results {
  position: absolute;
  top: 40px;
  left: 0;
  right: 0;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  max-height: 300px;
  overflow-y: auto;
  z-index: 999;
}

.search-result-item {
  padding: 10px 15px;
  cursor: pointer;
  border-bottom: 1px solid #ebeef5;
}

.search-result-item:hover {
  background-color: #f5f7fa;
}

.history-list {
  width: 100%;
}

.history-item {
  margin-bottom: 10px;
}

.mt-10px {
  margin-top: 10px;
}

.map-container {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
  width: 100%;
}

.amap-wrapper {
  width: 300px;
  height: 200px;
  border: 1px solid #ddd;
  position: relative;
  overflow: hidden;
}

.map-info {
  margin-left: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.map-info p {
  margin: 5px 0;
}

.location-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

/* 宗祠详情样式 - H5样式 */
.temple-detail-dialog :deep(.el-dialog__body) {
  padding: 0;
  background: #f8f9fa;
}

.temple-detail-container {
  max-height: 80vh;
  overflow-y: auto;
}

/* H5样式 - 顶部大图 */
.hero-section {
  position: relative;
  height: 250px;
  overflow: hidden;
}

.hero-image {
  width: 100%;
  height: 100%;
}

.hero-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.hero-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
  padding: 30px 20px 20px;
  color: white;
}

.hero-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.hero-subtitle {
  margin: 5px 0 0 0;
  font-size: 14px;
  opacity: 0.9;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

/* 信息卡片样式 */
.info-cards {
}

.info-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 16px;
  overflow: hidden;
}

.card-header {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
}

.card-header i {
  width: 20px;
  height: 20px;
  margin-right: 8px;
  background-size: contain;
  background-repeat: no-repeat;
  font-style: normal;
  font-size: 16px;
}

.card-header span {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.image-count {
  margin-left: auto;
  font-size: 12px;
  color: #999;
  font-weight: normal;
}

.card-content {
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.value {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.status-badge {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.active {
  background: #e6f7ff;
  color: #1890ff;
}

.status-badge.inactive {
  background: #fff2e8;
  color: #ff4d4f;
}

/* 地图样式 */
.map-container {
  position: relative;
}

.mini-map {
  width: 100%;
  height: 180px;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 10px;
  border: 1px solid #e8e8e8;
}

.coordinates {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
}

/* 简介样式 */
.intro-text,
.notes-text {
  font-size: 14px;
  line-height: 1.8;
  color: #666;
  text-align: justify;
}

/* 图片网格样式 */
.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 8px;
}

.image-item {
  aspect-ratio: 1;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.image-item:hover {
  transform: scale(1.05);
}

.image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 时间轴样式 */
.timeline {
  position: relative;
}

.timeline-item {
  display: flex;
  margin-bottom: 20px;
  position: relative;
}

.timeline-item::before {
  content: '';
  position: absolute;
  left: 8px;
  top: 16px;
  bottom: -20px;
  width: 2px;
  background: #e8e8e8;
}

.timeline-item:last-child::before {
  display: none;
}

.timeline-dot {
  width: 16px;
  height: 16px;
  background: #1890ff;
  border-radius: 50%;
  margin-right: 12px;
  flex-shrink: 0;
  margin-top: 2px;
}

.timeline-content {
  flex: 1;
}

.timeline-year {
  font-size: 14px;
  font-weight: 600;
  color: #1890ff;
  margin-bottom: 4px;
}

.timeline-text {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
}

.image-preview-dialog :deep(.el-dialog__body) {
  padding: 20px;
  text-align: center;
}

.preview-large-image {
  max-width: 100%;
  max-height: 70vh;
  border-radius: 8px;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .hero-section {
    height: 200px;
  }
  
  .hero-title {
    font-size: 20px;
  }
  
  .info-cards {
    padding: 15px;
  }
  
  .image-grid {
    grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
    gap: 6px;
  }
}
</style>
